﻿using System.Collections.Generic;
using System.Data;
using System.Linq;
using MySql.Data.MySqlClient;
using Spider.Framework.DataAccess;
using Spider.Framework.UtilityCommon.Extensions;
using System.Web.Script.Serialization;
using System;

namespace MyCrawler.Entity
{
    public class ContentBO
    {
        private const string con = Config.conn;
        
        /// <summary>
        /// Thêm mới mẩu tin
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public long AddNew(ContentEntity entity)
        {
            const string sql = "INSERT INTO contents(title, summury, content, category, comments, link, file, lastmodify) " +
                              "VALUES(@title, @summury, @content, @category, @comments, @link, @file, @lastmodify)";

            JavaScriptSerializer json_serializer = new JavaScriptSerializer();
            var comments = entity.Comments != null && entity.Comments.Count > 0
                ? json_serializer.Serialize(entity.Comments)
                : string.Empty;

            var param = new[]
                            {
                                new MySqlParameter("@link", entity.Link),
                                new MySqlParameter("@file", entity.File),
                                new MySqlParameter("@comments", comments),
                                new MySqlParameter("@title", entity.Title),
                                new MySqlParameter("@summury", entity.Summury),
                                new MySqlParameter("@content", entity.Content),
                                new MySqlParameter("@category", entity.Category),
                                new MySqlParameter("@lastmodify", entity.LastModify),
                            };
            entity.Id = (new MySqlBaseDAO(con)).ExeNonQuery(sql, param).ToInt64();
            return entity.Id;
        }

        /// <summary>
        /// cập nhật comment nếu nó tồn tại
        /// </summary>
        /// <param name="url"></param>
        /// <param name="comment"></param>
        public bool UpdateComment(string url, string comment, string file)
        {
            try
            {
                string q = "update content set comments=@comments,file=@file where link=@link";
                var param = new[]
                            {
                                new MySqlParameter("@comments", comment),
                                new MySqlParameter("@file", file),
                                new MySqlParameter("@link", url)
                            };

                (new MySqlBaseDAO(con)).ExeNonQuery(q, param).ToInt64();
                return true;
            }
            catch(Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// xóa các record trùng link - nếu có
        /// </summary>
        /// <param name="id"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public bool DeleteSameLink(long id, string url)
        {
            try
            {
                string q = "delete from contents where id != @id and link = @link";
                var param = new[]
                            {
                                new MySqlParameter("@id", id),
                                new MySqlParameter("@link", url),
                            };

                (new MySqlBaseDAO(con)).ExeNonQuery(q, param).ToInt64();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// lấy 10,000 record gần nhất
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, long> SelectList()
        {
            var dic = new Dictionary<string, long>();
            const string sql = "SELECT id, link FROM content Where ORDER BY id DESC LIMIT 10000";

            MySqlBaseDAO msbase = new MySqlBaseDAO(con);
            var dt = msbase.ExeDataTable(sql);

            if (dt.IsNullOrEmpty()) return null;

            foreach (var item in dt.Rows.Cast<DataRow>()
                .Select(c => new ContentEntity
                                 {
                                     Id = c.IsNull("id") ? 0 : c["id"].ToInt32(),
                                     Link = c.IsNull("link") ? string.Empty : c["link"].ToString(),
                                 })
                .Where(c => !dic.ContainsKey(c.Link)))
                dic.Add(item.Link, item.Id);
            return dic;
        }

        /// <summary>
        /// lấy danh sách link có điều kiện
        /// </summary>
        /// <param name="domain"></param>
        /// <returns></returns>
        public Dictionary<string, long> GetList(string domain)
        {
            var dic = new Dictionary<string, long>();
            string sql = "SELECT id, link FROM content Where link like '%" + domain + "%' ORDER BY id DESC LIMIT 2000";
            
            MySqlBaseDAO msbase = new MySqlBaseDAO(con);
            var dt = msbase.ExeDataTable(sql);

            if (dt.IsNullOrEmpty()) return null;

            foreach (var item in dt.Rows.Cast<DataRow>()
                .Select(c => new ContentEntity
                {
                    Id = c.IsNull("id") ? 0 : c["id"].ToInt32(),
                    Link = c.IsNull("link") ? string.Empty : c["link"].ToString(),
                })
                .Where(c => !dic.ContainsKey(c.Link)))
                dic.Add(item.Link, item.Id);
            return dic;
        }

        /// <summary>
        /// Lấy danh sách các Id, Link đã lưu trong database
        /// </summary>
        /// <param name="domain"></param>
        /// <returns></returns>
        public Dictionary<string, long> GetListToList(string domain)
        {
            Dictionary<string, long> dic = new Dictionary<string, long>();

            string sql = "SELECT id, link FROM contents ORDER BY id DESC LIMIT 100000";
            try
            {
                MySqlBaseDAO msbase = new MySqlBaseDAO(con);
                var dt = msbase.ExeDataTable(sql);

                if (dt.IsNullOrEmpty()) return null;

                foreach (var item in dt.Rows.Cast<DataRow>())
                {
                    if (!dic.ContainsKey(item[1].ToString()))
                    {
                        dic.Add(item[1].ToString(), Convert.ToInt64(item[0]));
                    }
                }
            }
            catch
            { }
            return dic;
        }
    }
}